package cn.swenty.backstage.framework.common.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import cn.swenty.backstage.framework.common.FormMap;

/**
 * @author sunyang
 *
 */
public class Bean2MapUtils {
	
	
	/**
	 * list-map转成list-object
	 * @param maps
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static <T>  List<T> maps2Objects(List<? extends FormMap> maps,Class<T> beanClass) throws Exception {
		List<T> list  = new ArrayList<T>();
		for(FormMap form:maps){
			list.add(map2Object(form, beanClass));
		}
		return list;
	}
	
	
	/**
	 * 对象转成maps
	 * @param objects
	 * @return
	 * @throws Exception
	 */
	public static List<FormMap> objects2Maps(List<Object> objects) throws Exception {
		List<FormMap> list  = new ArrayList<FormMap>();
		for(Object  form:objects){
			list.add(object2Map(form));
		}
		return list;
	}
	
	
	/**
	 * 根据map制造map
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static <T> T map2Object(FormMap map, Class<T> beanClass) {    
		 if (map == null)  
	            return null;  
	  
	        T obj = null;
			try {
				obj = beanClass.newInstance();
				 org.apache.commons.beanutils.BeanUtils.populate(obj, map);
			} catch (InstantiationException | IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}  
	  
        return obj;    
    }    
  
    /**
     * 
     * 根据object产生map
     * @param obj
     * @return
     * @throws Exception
     */
    public static FormMap object2Map(Object obj) throws Exception {    
    	 if(obj == null)  
             return null;   
    	 FormMap fm =  new FormMap();
         fm.putAll(new org.apache.commons.beanutils.BeanMap(obj));
         return fm;
    }   

}
